/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import java.util.HashMap;
import java.util.Map;
import org.nop.core.BeanScope;
import org.nop.core.ManagedBean;
import org.nop.markup.MarkupParser;
import org.nop.markup.MarkupRenderer;
import org.nop.markup.tree.MarkupText;
import org.nop.templating.Template;
import org.xthl.core.api.BlockLogic;
import org.xthl.core.api.CustomBlock;

/**
 *
 * @author Alexey Andreev
 */
@ManagedBean(iface = BlockCache.class, scope = BeanScope.APPLICATION)
public class BlockCacheImpl implements BlockCache {
    private static class CachedBlock {
        public final MarkupText text;
        public final int version;
        
        public CachedBlock(MarkupText text, int version) {
            this.text = text;
            this.version = version;
        }
    }
    private Map<Integer, CachedBlock> blocks = new HashMap<Integer, CachedBlock>();

    @Override
    public synchronized Template getCustomBlockContent(CustomBlock block, BlockLogic logic) {
        CachedBlock cachedBlock = blocks.get(block.getId());
        if (cachedBlock == null || cachedBlock.version != block.getVersion()) {
            MarkupParser parser = new MarkupParser();
            String content = logic.getCustomBlockContent(block.getId());
            MarkupText text = parser.parse(content);
            cachedBlock = new CachedBlock(text, block.getVersion());
            blocks.put(block.getId(), cachedBlock);
        }
        return new MarkupRenderer(cachedBlock.text);
    }
}
